package com.marktotop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.marktotop.entity.business.Health;
import com.marktotop.entity.system.Log;
import com.marktotop.error.BusinessCodeEnum;
import com.marktotop.error.BusinessException;
import com.marktotop.mapper.HealthMapper;
import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IHealthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-07-12
 */
@Service
public class HealthServiceImpl extends ServiceImpl<HealthMapper, Health> implements IHealthService {

    @Autowired
    private HealthMapper healthMapper;


    /**
     * 进行健康上报
     *
     * @param health
     * @return
     * @throws BusinessException
     */
    @Override
    public boolean report(Health health) throws BusinessException {
        Health report = isReported(health.getUserId());
        if(null != report) {
            throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR, "今日已经打卡,无法重复打卡！");
        }
        health.setCreateTime(new Date());
        if (healthMapper.insert(health) == 0){
            return false;
        }
        return true;
    }


    /**
     * 今日是否已报备
     * @param id
     * @return
     */
    @Override
    public Health isReported(Long id) {
        List<Health> health = healthMapper.isReport(id);
        if(health.size() > 0){
            return  health.get(0);
        }
        return null;
    }


    /**
     * 分页展示当前登录用户的健康上报记录
     *
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResultBean history(Long id, Integer pageNum, Integer pageSize) {
        // 开启分页
        Page<Health> page = new Page<>(pageNum,pageSize);
        IPage<Health> histories = healthMapper.getHistoryByPage(page,id);
        if (null == histories){
            return ResultBean.result(ResultCode.NON_RESULT);
        }
        return ResultBean.ok().message("获取健康上报日志信息成功！")
                .data("total",histories.getTotal())
                .data("historyList",histories.getRecords());
    }
}
